<?php
use App\Services\Common\AdminService;
use App\Http\Controllers\Auth\Admin as AdminAuth;
use App\Http\Controllers\Auth\User as UserAuth;
if (!function_exists('admin')) {
    function admin($throw = false) {
        return AdminAuth::getInstance($throw);
    }
}
if (!function_exists('user')) {
    function user($throw = false) {
        return UserAuth::getInstance($throw);
    }
}
if (!function_exists('create_btn_by_code')) {
    function create_btn_by_code($code, $requestParams = [])
    {
        $admin = \admin(true)->admin();
        $menus = AdminService::getPermissionCache($admin);
        $menus = json_decode($menus, true);
        $menu  = null;
        foreach ($menus as $k => $v) {
            if ($v['menu_no'] == $code) $menu = $v;
        }

        if (!$menu) return '';
        $menu = (object)$menu;
        $uri  = $menu->uri . '?code=' . $menu->menu_no;
        if (collect($requestParams)->count()) {
            \Log::info($requestParams);
            foreach ($requestParams as $k => $v) {
                $uri .= "&{$k}={$v}";
            }
        }
        $btnType   = $menu->btn_type;
        $eventName = explode('-', $menu->menu_no);
        $eventName = end($eventName);
        if ($menu->menu_no == 'systemConfig-save') $eventName = 'systemConfig-save';
        if ($menu->icon) {
            $btnText = "<i class='layui-icon {$menu->icon}'></i>";
        } else {
            $btnText = $menu->name;
        }
        switch ($btnType) {
            case \App\Constant\Constant::BtnType_Default:
                $html = "<button class='layui-btn layui-btn-xs {$menu->class_name}' lay-event='operate' request-uri='{$uri}' title='{$menu->name}'>{$btnText}</button>";
                break;
            case \App\Constant\Constant::BtnType_Query:
                $html = "<button type='button' class='layui-btn {$menu->class_name}' lay-filter='{$eventName}' lay-submit request-uri='{$uri}' title='{$menu->name}'>{$btnText}</button>";
                break;
            case \App\Constant\Constant::BtnType_Export:
                $html = "<button class='layui-btn layui-btn-xs {$menu->class_name}' lay-filter='{$eventName}' lay-submit request-uri='{$uri}' title='{$menu->name}'>{$btnText}</button>";
                break;
            case \App\Constant\Constant::BtnType_Win:
                $html = "<button class='layui-btn layui-btn-xs {$menu->class_name}' lay-event='open' request-uri='{$uri}' title='{$menu->name}'>{$btnText}</button>";
                break;
            case \App\Constant\Constant::BtnType_Save:
                $html = "<button class='layui-btn {$menu->class_name}' lay-filter='{$eventName}' lay-submit request-uri='{$uri}' title='{$menu->name}'>{$btnText}</button>";
                break;
            case \App\Constant\Constant::BtnType_Down:
                $html = "<button class='layui-btn layui-btn-xs {$menu->class_name}' lay-filter='{$eventName}' request-uri='{$uri}' title='{$menu->name}'>{$btnText}</button>";
                break;
        }
        return $html;
    }
}

if (!function_exists('list_go_tree')) {
    function list_go_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent             = &$refer[$parentId];
                        $list[$key]['name'] = $list[$key]['name'];
                        $parent[$child][]   = &$list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('array_to_tree')) {
    function array_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $list[$key][$child] = [];
                $refer[$data[$pk]]  =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('map_to_options')) {
    function map_to_options($map)
    {
        $data = [];
        foreach ($map as $key => $value) {
            $data[] = [
                'value' => $key,
                'label' => $value
            ];
        }
        return $data;
    }
}

if (!function_exists('is_local')) {
    /**
     * @return bool
     */
    function is_local()
    {
        return config('app.env') == 'local';
    }
}

if (!function_exists('is_production')) {
    /**
     * @return bool
     */
    function is_production()
    {
        return config('app.env') == 'production';
    }
}

if (!function_exists('is_lisa')) {
    /**
     * @return bool
     */
    function is_lisa()
    {
        return config('app.env') == 'lisa';
    }
}

if (!function_exists('array_get')) {
    /**
     * @param $array
     * @param $key
     * @param null $default
     * @return mixed
     */
    function array_get($array, $key, $default = null)
    {
        if (!array_accessible($array)) {
            return value($default);
        }

        if (is_null($key)) {
            return $array;
        }

        if (array_exits($array, $key)) {
            return $array[$key];
        }

        if (strpos($key, '.') === false) {
            return $array[$key] ?? value($default);
        }

        foreach (explode('.', $key) as $segment) {
            if (array_accessible($array) && array_exits($array, $segment)) {
                $array = $array[$segment];
            } else {
                return value($default);
            }
        }

        return $array;
    }
}

if (!function_exists('array_exists')) {
    /**
     * @param $array
     * @param $key
     * @return bool
     */
    function array_exits($array, $key)
    {
        if ($array instanceof ArrayAccess) {
            return $array->offsetExists($key);
        }
        return array_key_exists($key, $array);
    }
}

if (!function_exists('array_accessible')) {
    /**
     * @param $array
     * @return bool
     */
    function array_accessible($array)
    {
        return is_array($array) || $array instanceof ArrayAccess;
    }
}

if (!function_exists('array_to_tree')) {
    function array_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $list[$key][$child] = [];
                $refer[$data[$pk]]  =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}


if (!function_exists('get_microsecond')) {
    /**
     * 获取当前微秒数
     * @return float
     */
    function get_microsecond()
    {
        list($micro, $sec) = explode(" ", microtime());

        return ((float)$micro + (float)$sec);
    }
}

if (!function_exists('get_m_sec_time')) {
    /**
     * 获取当前毫秒时间戳
     * @return int
     */
    function get_m_sec_time()
    {
        list($mSec, $sec) = explode(' ', microtime());
        $mSecTime = (float)sprintf('%.0f', (floatval($mSec) + floatval($sec)) * 1000);
        return (int)$mSecTime;
    }
}

if (!function_exists('m_to_time')) {
    /**
     * 毫秒时间戳转秒
     * @param $timestamp
     * @return int
     */
    function m_to_time($timestamp)
    {
        return intval($timestamp / 1000);
    }
}

if (!function_exists('is_qiniu')) {
    function is_qiniu()
    {
        return config('common.cloud_storage') === 'qiniu';
    }
}

if (!function_exists('set_array_by_keys')) {
    function set_array_by_keys($list, $keys)
    {
        $collection = collect($list);
        $grouped    = $collection->mapWithKeys(function ($item, $key) use ($keys) {
            if (is_array($keys)) {
                $items = [];
                foreach ($keys as $v) {
                    $items[] = $item[$v];
                }
                return [implode('-', $items) => $item];
            } else {
                return [$item[$keys] => $item];
            }
        });

        return $grouped->toArray();
    }
}

if (!function_exists('get_pluck_to_array')) {
    function get_pluck_to_array($list, $key)
    {
        $list = collect($list)->pluck($key)->unique()->values()->toArray();
        return array_values(array_filter($list));
    }
}
